from django.shortcuts import render_to_response
from django.utils import simplejson
from django import template
from django.http import HttpResponse
import re
from django.core import serializers 
from django.contrib import admin
from django.contrib.admin.options import *
from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from displayform import *
from django.contrib.admin.helpers import InlineAdminFormSet

from tjango.monedas.models import * 


def render_display_form(request, model, context, add=False, change=False, form_url='', obj=None):
        opts = model._meta
        app_label = opts.app_label
        ordered_objects = opts.get_ordered_objects()
        extra_context = {
            'add': add,
            'change': change,
	    'has_add_permission': admin.site._registry[model].has_add_permission(request),
            'has_change_permission': admin.site._registry[model].has_change_permission(request, obj),
            'has_delete_permission': admin.site._registry[model].has_delete_permission(request, obj),
            'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
            'has_absolute_url': hasattr(model, 'get_absolute_url'),
            'ordered_objects': ordered_objects,
            'form_url': mark_safe(form_url),
            'opts': opts,
            'content_type_id': ContentType.objects.get_for_model(model).id,
            'save_on_top': True,

        }
        context.update(extra_context)
        return render_to_response([
            "admin/%s/%s/display_form.html" % (app_label, opts.object_name.lower()),
            "admin/%s/display_form.html" % app_label,
            "admin/display_form.html"], context_instance=context)






def view_form(request, app_label, model_name, rest_of_url):
    "The 'change' admin view for this model."
    #print app_label, model_name, rest_of_url
    model = models.get_model(app_label, model_name)
    opts = model._meta
    myadmin = admin.site._registry[model]
    object_id = int(rest_of_url)
    
    
    # CAMBIAR PARA UN SUO GENERICO NO SOLO COM IMPRIMIR
    try:
    	actions= myadmin.actions
    except:
	actions = {}
	   
    #HASTA ACA
	   
	   
    try:
        obj = model._default_manager.get(pk=object_id)
    except model.DoesNotExist:
        # Don't raise Http404 just yet, because we haven't checked
        # permissions yet. We don't want an unauthenticated user to be able
        # to determine whether a given object exists.
        obj = None

    if not myadmin.has_change_permission(request, obj):
        raise PermissionDenied

    if obj is None:
        raise Http404('%s object with primary key %r does not exist.' % (opts.verbose_name, escape(object_id)))

    if request.POST and request.POST.has_key("_saveasnew"):
        return myadmin.add_view(request, form_url='../../add/')

    #ModelForm = admin.get_form(request, obj)
    cls_fields = [f.name for f in obj.__class__._meta.fields if f.name <> 'id']
    
    class MyForm2(DisplayModelForm):
			class Meta:
				model = obj.__class__
				fields= cls_fields
    
    inline_formsets = []
    if request.method == 'POST':
        #form = ModelForm(request.POST, request.FILES, instance=obj)
        
        form = MyForm2(cls = obj, instance = obj, display_only=True)
        form.Meta.model = obj.__class__
        form.test()
        for FormSet in myadmin.get_formsets(request, obj):
            inline_formset = FormSet(request.POST, request.FILES, instance=obj)
            inline_formsets.append(inline_formset)

        if all_valid(inline_formsets) and form.is_valid():
            return myadmin.save_change(request, model, form, inline_formsets)
    else:
        #form = ModelForm(instance=obj)
        form = MyForm2(cls = obj,instance = obj, display_only=True)
        form.Meta.model = obj.__class__
        for FormSet in myadmin.get_formsets(request, obj):
            inline_formset = FormSet(instance=obj)
            inline_formsets.append(inline_formset)

   # return render_to_response ('admin/display_form.html', {'form': form})
    
    
    adminForm = helpers.AdminForm(form, myadmin.get_fieldsets(request), myadmin.prepopulated_fields)
    #adminForm = admin.ModelAdmin(model, admin.site) #, admin.get_fieldsets(request, obj), admin.prepopulated_fields)
    media = myadmin.media + adminForm.media
    for fs in inline_formsets:
        media = media + fs.media

    inline_admin_formsets = []
    for inline, formset in zip(myadmin.inline_instances, inline_formsets):
        fieldsets = list(inline.get_fieldsets(request, obj))
        inline_admin_formset = InlineAdminFormSet(inline, formset, fieldsets)
        inline_admin_formsets.append(inline_admin_formset)
    c = template.RequestContext(request, {
        'title': 'Ver %s' % opts.verbose_name,
        'adminform': adminForm,
        'object_id': object_id,
        'original': obj,
        'is_popup': request.REQUEST.has_key('_popup'),
        'media': mark_safe(media),
	'actions': actions,
        'inline_admin_formsets': inline_admin_formsets,
    })
    #return render_to_response ('admin/display_form.html', {'adminform':adminForm, 'form': form} )
    return render_display_form(request, model, c, change=True, obj=obj)



